//
// MDragger.java
//
package com.photoexpert;

import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

class MDragger implements MouseListener, MouseMotionListener {

    static MDragger Instance() {
        if(_instance == null) {
            _instance = new MDragger();
            Presentor.Instance().addMouseListener(_instance);
            Presentor.Instance().addMouseMotionListener(_instance);
        }
        return _instance;
    }

    void reset() {
        _mouseDown = false;
        _downX = 0;
        _downY = 0;
        _viewRect = null;
        _presentor.setCursor(Cursors._moveCursor);
    }


    @Override
    public void mouseClicked(MouseEvent e) {
        if(_presentor.getMouseMode() != Presentor.MOUSE_MODES.DRAGGING)
            return;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if(_presentor.getMouseMode() != Presentor.MOUSE_MODES.DRAGGING)
            return;
        _mouseDown = true;
        _downX = e.getX();
        _downY = e.getY();
        _viewRect = _presentor.getVisibleRect();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if(_presentor.getMouseMode() != Presentor.MOUSE_MODES.DRAGGING)
            return;
        reset();
    }

    @Override
    public void mouseEntered(MouseEvent e) { }

    @Override
    public void mouseExited(MouseEvent e) { }

    @Override
    public void mouseDragged(MouseEvent e) {
        if(_presentor.getMouseMode() != Presentor.MOUSE_MODES.DRAGGING)
            return;
        if(!_mouseDown)
            return;
        int diffX = e.getX() - _downX;
        int diffY = e.getY() - _downY;
        if(diffX < 10 && diffX > -10)
            diffX = 0;
        if(diffY < 10 && diffY > -10)
            diffY = 0;
        if(diffX != 0 || diffY != 0) {
            _viewRect.x -= diffX;
            if(_viewRect.x < 0)
                _viewRect.x = 0;
            _viewRect.y -= diffY;
            if(_viewRect.y < 0)
                _viewRect.y = 0;
            _presentor.scrollRectToVisible(_viewRect);
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        if(_presentor.getMouseMode() != Presentor.MOUSE_MODES.DRAGGING)
            return;
    }

    private MDragger() { _presentor = Presentor.Instance(); }

    private static MDragger     _instance = null;
    private Presentor               _presentor = null;
    private boolean                 _mouseDown = false;
    private int                     _downX = 0;
    private int                     _downY = 0;
    private Rectangle               _viewRect = null;
}
